// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using System;
using KnessetCore.Updaters;
using KnessetCore.Utils;
using log4net;

namespace KnessetCore.Engines
{
	/// <summary>
	/// An engine that runs an updater object in a timely manner. The updater engine is assumed not to receive
	/// any parameter in its update method (i.e. null value).
	/// </summary>
	public class UpdaterEngine : Engine
	{
		/// <summary>
		/// An updater object.
		/// </summary>
		private readonly IUpdater<object> updater;
		
		/// <summary>
		/// Used in order to log data.
		/// </summary>
		private readonly ILog logger = LogManager.GetLogger("KnessetCore.Engine"); 
		
		/// <summary>
		/// Create a new object.
		/// </summary>
		/// <param name="updater">An updater to use. Pay attention to the fact that the updater may receive null
		/// value as a parameter.</param>
		public UpdaterEngine(IUpdater<object> updater)
		{
			if (updater == null) throw new ArgumentNullException("updater");
			this.updater = updater;
		}

		/// <summary>
		/// Run a single engine operation.
		/// </summary>
		public override void Start()
		{
			try
			{
				updater.Update(null);
			}
			catch (Exception e)
			{
				
				// In case we have an inner error print it instead of this error.
				if (e.InnerException != null)
				{
					e = e.InnerException;
				}
				logger.Error(string.Format("Error while running engine: {0}\nStack: {1}", e.Message, e.StackTrace));
				Constants.CriticalErrorLogger.Error(string.Format("Error while running engine: {0}\nStack: {1}", e.Message, e.StackTrace));
			}
		}
	}
}